﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Microsoft.Office.Interop.Word;
using Microsoft.Win32;
using Project5188.BUS;
using Project5188.BUS.EducationAndTraining;
using Project5188.BUS.Operations;
using Project5188.BUS.SalesAndCustomerRelations;
using Project5188.Client.ClientCodes;
using VIBlend.WPF.Controls;
using Button = System.Windows.Controls.Button;
using CheckBox = System.Windows.Controls.CheckBox;
using DatePicker = Microsoft.Windows.Controls.DatePicker;
using Image = System.Drawing.Image;
using WORD = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;

namespace Project5188.Client
{
    /// <summary>
    /// Interaction logic for UpdateWindow.xaml
    /// </summary>
    public partial class UpdateWindow
    {
        private Dictionary<string, resource> _resourceDic;
        private static PropertyInfo[] _propertyInfos;
        private static dynamic _detailEntity;
        private readonly List<string> _numericControls = new List<string>();
        private string _version;
        private string _pageName;
        private long _documentId;
        private bool _isApproved;
        private long _transactionId;

        public UpdateWindow()
        {
            InitializeComponent();

            TransactionInfo.TransactionId = null;
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            if (_numericControls.Contains(((FrameworkElement)(e.OriginalSource)).Name))
            {
                e.Handled = !PageBase.AreAllValidNumericChars(e.Text);
            }
            base.OnPreviewTextInput(e);
        }

        public void SetEntity<T>(DetailView<T> detail, string pageName, params long[] parameters)
        {
            if (detail == null) throw new ArgumentNullException("detail");

            _pageName = pageName;

            _resourceDic = BUS.Resources.GetResourceByPageName(pageName);

            _transactionId = parameters[0];

            //detail.Entity = detail.GetEntity();
            detail.EntityList = detail.GetEntityById(parameters[0]);
            detail.Entity = detail.EntityList[0];
            _detailEntity = detail;

            var propertyInfos = detail.Entity.GetType().GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
                // ReSharper disable PossibleNullReferenceException
                if (!(propertyInfo.PropertyType).FullName.Contains("Data") &&
                    // ReSharper restore PossibleNullReferenceException
                    !(propertyInfo.PropertyType).FullName.Contains("Project5188") &&
                    propertyInfo.Name != "IsDeleted" &&
                    propertyInfo.Name != "ModifyBy" &&
                    propertyInfo.Name != "ModifyDate" &&
                    propertyInfo.Name != "CreateBy")
                {
                    var value = propertyInfo.GetValue(detail.EntityList[0], null);

                    resource resourceKey;
                    _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);

                    var lblHeader = new Label
                                        {
                                            Name = "lbl" + propertyInfo.Name,
                                            Content =
                                                resourceKey != null
                                                    ? resourceKey.Value + " : "
                                                    : propertyInfo.Name + " : ",
                                            Height = 23,
                                            HorizontalContentAlignment = HorizontalAlignment.Left
                                        };

                    RegisterName(lblHeader.Name, lblHeader);
                    StackPanel1.Children.Add(lblHeader);

                    var lblEmpty = new Label {Height = 10};
                    StackPanel1.Children.Add(lblEmpty);

                    if (pageName == Extensions.PageNames.DocumentPage.ToString() && propertyInfo.Name == "a_ID")
                    {
                        _documentId = Convert.ToInt64(value);
                    }

                    if (propertyInfo.Name.Contains("ParameterValueID"))
                    {
                        string parameterId = propertyInfo.Name.Split('_')[2];
                        var parameterValues = new ParameterValues();

                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["comboTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   parameterValues.GetEntityByParameterId(
                                                       (Convert.ToInt64(parameterId))),
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               IsEditable = false
                                           };

                        drpValue.SelectedValue = value;

                        if (pageName == Extensions.PageNames.DocumentPage.ToString())
                        {
                            switch (propertyInfo.Name)
                            {
                                case "c_DocumentTypeParameterValueID_30":
                                    drpValue.IsEnabled = false;
                                    break;
                                case "h_FlowTypeParameterValueID_31":
                                    drpValue.IsEnabled = false;
                                    drpValue.SelectedValue = 388;
                                    break;
                                case "i_DocFlowTypeParameterValueID_28":
                                    drpValue.IsEnabled = false;
                                    break;
                                case "e_VersionIncTypeParameterValueID_29":
                                    drpValue.SelectionChanged += DrpValueSelectionChanged;
                                    break;
                            }
                        }

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty2 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty2);
                    }
                    else if ((pageName == Extensions.PageNames.CommunicationInfoPage.ToString() ||
                              pageName == Extensions.PageNames.DinnerExpenseDetailPage.ToString() ||
                              pageName == Extensions.PageNames.DressInfoPage.ToString() ||
                              pageName == Extensions.PageNames.IdCardInfoPage.ToString() ||
                              pageName == Extensions.PageNames.InsuranceInfoPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelActionPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelNomineePage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelWorkOutPage.ToString() ||
                              pageName == Extensions.PageNames.PersonnelInspectionPage.ToString()) &&
                             propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1] == "PersonnelID")
                    {
                        var personelInfos = new PersonnelInfos();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "a_ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["personnelTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   personelInfos.GetEntityList(),
                                               HorizontalAlignment = HorizontalAlignment.Right
                                           };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty6 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty6);
                    }
                    else if ((pageName == Extensions.PageNames.CustomerSalesInfoPage.ToString() || 
                        pageName == Extensions.PageNames.CreateOfferPage.ToString()) &&
                             propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1] == "CustomerInfoID")
                    {
                        var customerInfos = new CustomerInfos();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                            // ReSharper restore UseObjectOrCollectionInitializer
                                           {
                                               Name = "drp" + propertyInfo.Name,
                                               SelectedValuePath = "a_ID",
                                               IsSynchronizedWithCurrentItem = true,
                                               ItemTemplate = Resources["customerTemplate"] as DataTemplate,
                                               Width = 200,
                                               Height = 23,
                                               ItemsSource =
                                                   customerInfos.GetEntityList(),
                                               HorizontalAlignment = HorizontalAlignment.Right
                                           };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty7 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty7);
                    }
                    else if ((pageName == Extensions.PageNames.DocumentPage.ToString()) &&
                    propertyInfo.Name.Split('_').Length > 1 &&
                    propertyInfo.Name.Split('_')[1].Contains("UserID"))
                    {
                        var users = new Users();
// ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
// ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["usersTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                users.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right,
                            IsEnabled = false
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty14 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty14);
                    }
                    else if ((pageName == Extensions.PageNames.InspectionInfoPage.ToString() ||
                        pageName == Extensions.PageNames.InstitutionInspectionPage.ToString()) && 
                        propertyInfo.Name.Split('_').Length > 1 && 
                        propertyInfo.Name.Split('_')[1] == "InstitutionID")
                    {
                        var institutions = new Institutions();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["institutionTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                institutions.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty8 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty8);
                    }
                    else if ((pageName == Extensions.PageNames.CoursePage.ToString()) &&
                    propertyInfo.Name.Split('_').Length > 1 &&
                    propertyInfo.Name.Split('_')[1] == "TeacherID")
                    {
                        var teacherRegistries = new TeacherRegistries();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["teacherRegistryTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                teacherRegistries.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty9 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty9);
                    }
                    else if ((pageName == Extensions.PageNames.RollCallPage.ToString() ||
                        pageName == Extensions.PageNames.SuccessStatusPage.ToString()) && 
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1] == "StudentID")
                    {
                        var studentRegistries = new StudentRegistries();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["studentRegistryTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                studentRegistries.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty10 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty10);
                    }
                    else if ((pageName == Extensions.PageNames.RollCallPage.ToString()) &&
                            propertyInfo.Name.Split('_').Length > 1 &&
                            propertyInfo.Name.Split('_')[1] == "TimeTableID")
                    {
                        var timeTables = new TimeTables();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["timeTablesTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                timeTables.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty11 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty11);
                    }
                    else if ((pageName == Extensions.PageNames.SuccessStatusPage.ToString() ||
                        pageName == Extensions.PageNames.TimeTablePage.ToString()) &&
                        propertyInfo.Name.Split('_').Length > 1 &&
                        propertyInfo.Name.Split('_')[1] == "CourseID")
                    {
                        var courses = new Courses();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "a_ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["coursesTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                courses.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty12 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty12);
                    }
                    else if ((pageName == Extensions.PageNames.UserPage.ToString()) &&
                        propertyInfo.Name == "RoleGroupID")
                    {
                        var roleGroups = new RoleGroups();
                        // ReSharper disable UseObjectOrCollectionInitializer
                        var drpValue = new ComboBox
                        // ReSharper restore UseObjectOrCollectionInitializer
                        {
                            Name = "drp" + propertyInfo.Name,
                            SelectedValuePath = "ID",
                            IsSynchronizedWithCurrentItem = true,
                            ItemTemplate = Resources["roleGroupsTemplate"] as DataTemplate,
                            Width = 200,
                            Height = 23,
                            ItemsSource =
                                roleGroups.GetEntityList(),
                            HorizontalAlignment = HorizontalAlignment.Right
                        };

                        drpValue.SelectedValue = value;

                        RegisterName(drpValue.Name, drpValue);
                        StackPanel2.Children.Add(drpValue);

                        var lblEmpty13 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty13);
                    }
                    else if ((propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].StartsWith("Is")) ||
                             propertyInfo.Name.StartsWith("Is"))
                    {
                        var chkValue = new CheckBox
                                           {
                                               Name = "chk" + propertyInfo.Name,
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               Height = 23,
                                               IsChecked = value == null ? false : (bool) value
                                           };

                        RegisterName(chkValue.Name, chkValue);
                        StackPanel2.Children.Add(chkValue);

                        var lblEmpty3 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty3);
                    }
                    else if (propertyInfo.Name.Contains("Date") && propertyInfo.PropertyType == typeof(DateTime))
                    {
                        var dtValue = new DatePicker
                                          {
                                              Name = "dt" + propertyInfo.Name,
                                              Width = 200,
                                              Height = 23,
                                              HorizontalAlignment = HorizontalAlignment.Right,
                                              SelectedDate =
                                                  ((DateTime) value) != DateTime.MinValue
                                                      ? (DateTime) value
                                                      : (DateTime?) null
                                          };

                        RegisterName(dtValue.Name, dtValue);
                        StackPanel2.Children.Add(dtValue);

                        var lblEmpty4 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty4);
                    }
                    else if (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].Contains("ImagePath"))
                    {
                        var imageButton = new Button
                                              {
                                                  Name = "btnAddImage",
                                                  Content = "...",
                                                  Height = 23,
                                                  Width = 40,
                                                  HorizontalAlignment = HorizontalAlignment.Right
                                              };

                        imageButton.Click += ImageButtonClick;

                        StackPanel2.Children.Add(imageButton);

                        var txtValue = new TextBox
                                           {
                                               Name = "txtImagePath",
                                               Height = 23,
                                               Width = 150,
                                               Margin =
                                                   new Thickness(imageButton.Margin.Left,
                                                                 imageButton.Margin.Top - 23,
                                                                 imageButton.Margin.Right - 210,
                                                                 imageButton.Margin.Bottom),
                                               IsEnabled = false
                                           };

                        RegisterName(txtValue.Name, txtValue);
                        StackPanel2.Children.Add(txtValue);

                        var lblEmpty2 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty2);

                        var buffer = (byte[]) value;
                        var stream1 = new MemoryStream(buffer);
                        var image = Image.FromStream(stream1);

                        var bmp = new Bitmap(image);
                        var hBitmap = bmp.GetHbitmap();
                        System.Windows.Media.ImageSource imageSource =
                            System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero,
                                                                                         Int32Rect.Empty,
                                                                                         BitmapSizeOptions.
                                                                                             FromEmptyOptions());

                        var img = new System.Windows.Controls.Image
                                      {
                                          Name = "imgPersonnel",
                                          Source = imageSource,
                                          HorizontalAlignment = HorizontalAlignment.Left,
                                          Width = image.Width,
                                          Height = image.Height
                                      };

                        RegisterName(img.Name, img);
                        StackPanelImage.Children.Add(img);
                    }
                    else if (propertyInfo.PropertyType == typeof(decimal))
                    {
                        var decimalBox = new NumberEditor
                        {
                            Name = "dcb" + propertyInfo.Name,
                            Height = 23,
                            Width = 200,
                            HorizontalAlignment = HorizontalAlignment.Right,
                            CultureInfo = CultureInfo.InvariantCulture,
                            DecimalPlaces = 2,
                            SpinType = SpinType.SpinDigit,
                            EnableDefaultValidation = true,
                            Maximum = 99999999999,
                            Minimum = 0,
                            MaxLength = 11,
                            Text = value == null ? String.Empty : value.ToString()
                        };

                        decimalBox.ValidationFailed += DecimalBoxValidationFailed;

                        RegisterName(decimalBox.Name, decimalBox);
                        StackPanel2.Children.Add(decimalBox);

                        var lblEmpty2 = new Label { Height = 10 };
                        StackPanel2.Children.Add(lblEmpty2);
                    }
                    else
                    {
                        var txtValue = new TextBox
                                           {
                                               Name = "txt" + propertyInfo.Name,
                                               Height = 23,
                                               Width = 200,
                                               HorizontalAlignment = HorizontalAlignment.Right,
                                               Text = value == null ? String.Empty : value.ToString()
                                           };

                        if (propertyInfo.PropertyType == typeof(string) &&
                                (propertyInfo.Name.Contains("Email") ||
                                propertyInfo.Name.ToLower().Contains("name") ||
                                propertyInfo.Name.Contains("AuthorsOffer") ||
                                propertyInfo.Name.Contains("Section")))
                        {
                            txtValue.MaxLength = 150;
                        }
                        else if (propertyInfo.PropertyType == typeof(string) &&
                            (propertyInfo.Name.Contains("Explanation") ||
                            propertyInfo.Name.Contains("Address") ||
                            propertyInfo.Name.Contains("FirmsEarlierWork") ||
                            propertyInfo.Name.Contains("Detail") ||
                            propertyInfo.Name.Contains("ActionTaken") ||
                            propertyInfo.Name.Contains("CompanyLetterhead") ||
                            propertyInfo.Name.Contains("TextContext") ||
                            propertyInfo.Name.Contains("Value") ||
                            propertyInfo.Name.Contains("ReceivedAward") ||
                            propertyInfo.Name.Contains("WhatAwardGiven") ||
                            propertyInfo.Name.Contains("PenaltyInfo") ||
                            propertyInfo.Name.Contains("Content") ||
                            propertyInfo.Name.Contains("CertificateIssuePath") ||
                            propertyInfo.Name.Contains("Note") ||
                            propertyInfo.Name.Contains("Pass")))
                        {
                            txtValue.MaxLength = 255;
                        }
                        else if (propertyInfo.PropertyType == typeof(string))
                        {
                            txtValue.MaxLength = 50;
                        }
                        else if (propertyInfo.PropertyType == typeof(int))
                        {
                            txtValue.MaxLength = 11;
                        }

                        if (propertyInfo.PropertyType.Name.Contains("Int") &&
                            propertyInfo.PropertyType.Name != "Nullable`1")
                        {
                            _numericControls.Add(txtValue.Name);
                        }

                        if (pageName == Extensions.PageNames.ParameterValuePage.ToString())
                        {
                            switch (propertyInfo.Name)
                            {
                                case "ParameterID":
                                    txtValue.IsEnabled = false;
                                    txtValue.Text = parameters[1].ToString();
                                    break;
                                case "LanguageCode":
                                    txtValue.Text = "tr-TR";
                                    txtValue.IsEnabled = false;
                                    break;
                            }
                        }

                        if (pageName == Extensions.PageNames.DocumentPage.ToString())
                            {
                                switch (propertyInfo.Name)
                                {
                                    case "d_Version":
                                        txtValue.IsEnabled = false;
                                        if (value != null) _version = value.ToString();
                                        break;
                                }
                            }

                        if ((propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "ID") ||
                            propertyInfo.Name == "ID" ||
                            (pageName == Extensions.PageNames.DocumentFlowPage.ToString() && propertyInfo.Name == "b_DocumentID"))
                        {
                            txtValue.IsEnabled = false;
                        }

                        RegisterName(txtValue.Name, txtValue);
                        StackPanel2.Children.Add(txtValue);

                        var lblEmpty5 = new Label {Height = 10};
                        StackPanel2.Children.Add(lblEmpty5);
                    }
                }
            }

            if (StackPanelImage.Children.Count == 0)
            {
                StackPanel1.Margin = new Thickness(10, 10, 0, 0);
                StackPanel2.Margin = new Thickness(10, 10, 10, 0);
            }

            if (pageName == Extensions.PageNames.DocumentPage.ToString())
            {
                var imageButtonFile = new Button
                {
                    Name = "btnAddFile",
                    Content = "...",
                    Height = 23,
                    Width = 40,
                    HorizontalAlignment = HorizontalAlignment.Right
                };

                imageButtonFile.Click += ImageButtonFileClick;

                StackPanel2.Children.Add(imageButtonFile);

                var txtValue = new TextBox
                {
                    Name = "txtFilePath",
                    Height = 23,
                    Width = 150,
                    Margin =
                        new Thickness(imageButtonFile.Margin.Left,
                                      imageButtonFile.Margin.Top - 23,
                                      imageButtonFile.Margin.Right - 210,
                                      imageButtonFile.Margin.Bottom),
                    IsEnabled = false
                };

                RegisterName(txtValue.Name, txtValue);
                StackPanel2.Children.Add(txtValue);

                var lblEmpty2 = new Label { Height = 10 };
                StackPanel2.Children.Add(lblEmpty2);

                var txtVersion = (TextBox) FindName("txtd_Version");
                if (txtVersion != null && !String.IsNullOrEmpty(txtVersion.Text) && !String.IsNullOrWhiteSpace(txtVersion.Text))
                {
                    var cmbBox = (ComboBox) FindName("drpe_VersionIncTypeParameterValueID_29");
                    if (cmbBox != null && cmbBox.Items.Count > 0)
                    {
                        if (Convert.ToInt64(cmbBox.SelectedValue) == 378)
                        {
                            var version = Math.Floor(Convert.ToDouble(txtVersion.Text.Replace('.', ','))) + 1;
                            txtVersion.Text = String.Format("{0:0.0}", version).Replace(',','.');
                        }
                        else
                        {
                            var version = Convert.ToDouble(txtVersion.Text.Replace('.',',')) + 0.01;
                            txtVersion.Text = version.ToString().Replace(',', '.');
                        }
                    }
                }
            }

            var button = new Button
                             {
                                 Name = "btnUpdate",
                                 Content = "Güncelle",
                                 Margin = new Thickness(2, 2, 2, 2),
                                 Height = 23,
                                 Width = 100,
                                 HorizontalAlignment = HorizontalAlignment.Left
                             };

            button.Click += ButtonClick;

            StackPanel2.Children.Add(button);
        }

        void ImageButtonFileClick(object sender, RoutedEventArgs e)
        {
            var txtBox = (TextBox)FindName("txtFilePath");

            var openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = "C:\\",
                Filter =
                    "document files (*.doc)|*.doc",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            var result = openFileDialog1.ShowDialog();

            if (result == true)
            {
                if (txtBox != null)
                {
                    txtBox.Text = openFileDialog1.FileName;
                    txtBox.IsEnabled = false;
                }
            }
        }

        void DrpValueSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var txtVersion = (TextBox)FindName("txtd_Version");
            if (txtVersion == null || String.IsNullOrEmpty(txtVersion.Text) ||
                String.IsNullOrWhiteSpace(txtVersion.Text)) return;
            
            var cmbBox = (ComboBox)sender;
            if (cmbBox == null || cmbBox.Items.Count <= 0) return;
            
            if (Convert.ToInt64(cmbBox.SelectedValue) == 378)
            {
                var version = Math.Floor(Convert.ToDouble(_version.Replace('.', ','))) + 1;
                txtVersion.Text = String.Format("{0:0.0}", version).Replace(',', '.');
            }
            else
            {
                var version = Convert.ToDouble(_version.Replace('.', ',')) + 0.01;
                txtVersion.Text = version.ToString().Replace(',', '.');
            }
        }

        static void DecimalBoxValidationFailed(object sender, EventArgs e)
        {
            ((NumberEditor)sender).Value = 0;
            MessageBox.Show("Bu alana girebileceğiniz değerin uzunluğu max 11 olabilir!");
        }

        void ButtonClick(object sender, RoutedEventArgs e)
        {
            if (_detailEntity.Entity != null)
            {
                if (_pageName == Extensions.PageNames.DocumentPage.ToString())
                {
                    var cmbStatus = (ComboBox) FindName("drpg_DocumentStatusParameterValueID_27");

                    if (cmbStatus != null && cmbStatus.Items.Count > 0 &&
                        Convert.ToInt64(cmbStatus.SelectedValue) == 373)
                    {
                        var txtFileBox = (TextBox) FindName("txtFilePath");
                        var txtDocumentName = (TextBox) FindName("txtb_DocumentName");
                        var txtVersion = (TextBox) FindName("txtd_Version");
                        if (txtFileBox != null && !String.IsNullOrEmpty(txtFileBox.Text) &&
                            txtDocumentName != null && !String.IsNullOrEmpty(txtDocumentName.Text) &&
                            txtVersion != null && !String.IsNullOrEmpty(txtVersion.Text))
                        {
                            try
                            {
                                var parameterValues = new ParameterValues();
                                var serverPath = parameterValues.GetEntityByParameterId(32)[0].Value;
                                var directoryName = serverPath + "\\" + _documentId + "\\" + txtVersion.Text;

                                if (!Directory.Exists(directoryName))
                                {
                                    Directory.CreateDirectory(directoryName);
                                }

                                var missing = Type.Missing;

                                _Application word = new WORD.Application();

                                var doc = word.Documents.Open(txtFileBox.Text, ReadOnly: true, Visible: false);
                                doc.Activate();
                                doc.SaveAs(directoryName + "\\" + txtDocumentName.Text);
                                word.Quit(ref missing, ref missing, ref missing);

                                Marshal.ReleaseComObject(word);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Döküman Kaydetme Sırasında Hata Oluştu! \n Hata Detayı:" + ex.Message);
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Lütfen döküman seçiniz!");
                            return;
                        }
                    }
                }

                _propertyInfos = _detailEntity.Entity.GetType().GetProperties();

                foreach (var propertyInfo in _propertyInfos)
                {
                    // ReSharper disable PossibleNullReferenceException
                    if (!(propertyInfo.PropertyType).FullName.Contains("Data") &&
                        !(propertyInfo.PropertyType).FullName.Contains("Project5188"))
                        // ReSharper restore PossibleNullReferenceException
                    {
                        if (propertyInfo.Name.Contains("ParameterValueID") ||
                            (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "PersonnelID") ||
                            (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1] == "CustomerInfoID") ||
                            (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1] == "InstitutionID") ||
                            (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "TeacherID") ||
                            (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "StudentID") ||
                            (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "TimeTableID") ||
                            (propertyInfo.Name.Split('_').Length > 1 && propertyInfo.Name.Split('_')[1] == "CourseID") ||
                            (propertyInfo.Name == "RoleGroupID") ||
                            (propertyInfo.Name.Split('_').Length > 1 &&
                             propertyInfo.Name.Split('_')[1].Contains("UserID")))
                        {
                            var cmbBox = (ComboBox) FindName("drp" + propertyInfo.Name);
                            if (cmbBox != null)
                                propertyInfo.SetValue(_detailEntity.Entity,
                                                      Extensions.ChangeType(cmbBox.SelectedValue,
                                                                            propertyInfo.PropertyType),
                                                      null);
                        }
                        else if (propertyInfo.Name == "CreateBy")
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(UserInfo.UserId, propertyInfo.PropertyType),
                                                  null);
                        }
                        else if (propertyInfo.Name == "ModifyBy")
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(UserInfo.UserName, propertyInfo.PropertyType),
                                                  null);
                        }
                        else if (propertyInfo.Name == "ModifyDate")
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(DateTime.Now, propertyInfo.PropertyType),
                                                  null);
                        }
                        else if (propertyInfo.Name == "IsDeleted")
                        {
                            propertyInfo.SetValue(_detailEntity.Entity,
                                                  Extensions.ChangeType(false, propertyInfo.PropertyType), null);
                        }
                        else if ((propertyInfo.Name.Split('_').Length > 1 &&
                                  propertyInfo.Name.Split('_')[1].StartsWith("Is")) ||
                                 propertyInfo.Name.StartsWith("Is"))
                        {
                            var chkBox = (CheckBox) FindName("chk" + propertyInfo.Name);
                            if (chkBox != null)
                            {
                                propertyInfo.SetValue(_detailEntity.Entity,
                                                      Extensions.ChangeType(chkBox.IsChecked, propertyInfo.PropertyType),
                                                      null);

                                if (_pageName == Extensions.PageNames.DocumentFlowPage.ToString() &&
                                    chkBox.IsChecked.HasValue)
                                {
                                    if (chkBox.IsChecked.Value)
                                    {
                                        _isApproved = true;
                                    }
                                }
                            }
                        }
                        else if (propertyInfo.Name.Contains("Date") && propertyInfo.PropertyType == typeof (DateTime))
                        {
                            var dtValue = (DatePicker) FindName("dt" + propertyInfo.Name);
                            if (dtValue != null)
                            {
                                propertyInfo.SetValue(_detailEntity.Entity,
                                                      Extensions.ChangeType(
                                                          dtValue.SelectedDate.GetValueOrDefault(DateTime.MinValue),
                                                          propertyInfo.PropertyType),
                                                      null);
                            }
                        }
                        else if (propertyInfo.Name.Split('_').Length > 1 &&
                                 propertyInfo.Name.Split('_')[1].Contains("ImagePath"))
                        {
                            var txtImageBox = (TextBox) FindName("txtImagePath");
                            if (txtImageBox != null && !String.IsNullOrEmpty(txtImageBox.Text))
                            {
                                try
                                {
                                    // Load image.
                                    var image = Image.FromFile(txtImageBox.Text);

                                    // Compute thumbnail size.
                                    var thumbnailSize = Extensions.GetThumbnailSize(image);

                                    // Get thumbnail.
                                    var thumbnail = image.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height,
                                                                            null, IntPtr.Zero);

                                    using (var stream = new MemoryStream())
                                    {
                                        thumbnail.Save(stream, ImageFormat.Png);

                                        propertyInfo.SetValue(_detailEntity.Entity,
                                                              Extensions.ChangeType(stream.ToArray(),
                                                                                    propertyInfo.PropertyType),
                                                              null);
                                    }
                                    // Save thumbnail.
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Resim Kaydetme Sırasında Hata Oluştu! \n Hata Detayı:" + ex.Message);
                                    return;
                                }
                            }
                        }
                        else if (propertyInfo.PropertyType == typeof (decimal))
                        {
                            var decimalBox = (NumberEditor) FindName("dcb" + propertyInfo.Name);
                            if (decimalBox != null)
                            {
                                propertyInfo.SetValue(_detailEntity.Entity,
                                                      Extensions.ChangeType(decimalBox.Value, propertyInfo.PropertyType),
                                                      null);
                            }
                        }
                        else
                        {
                            var txtBox = (TextBox) FindName("txt" + propertyInfo.Name);
                            if (txtBox != null)
                            {
                                if (_numericControls.Contains(txtBox.Name) && String.IsNullOrEmpty(txtBox.Text))
                                {
                                    resource resourceKey;
                                    _resourceDic.TryGetValue(propertyInfo.Name, out resourceKey);
                                    MessageBox.Show(resourceKey.Value + " alanı boş geçilemez!");
                                    return;
                                }

                                if (propertyInfo.Name == "Pass")
                                {
                                    txtBox.Text = Extensions.Md5Hashing(txtBox.Text);
                                }

                                propertyInfo.SetValue(_detailEntity.Entity,
                                                      Extensions.ChangeType(txtBox.Text, propertyInfo.PropertyType),
                                                      null);

                                if (_pageName == Extensions.PageNames.DocumentFlowPage.ToString() &&
                                    propertyInfo.Name == "b_DocumentID")
                                {
                                    _documentId = Convert.ToInt64(txtBox.Text);
                                }
                            }
                        }
                    }
                }

                try
                {
                    _detailEntity.Update();
                    TransactionInfo.TransactionId = _transactionId;
                }
                catch (Exception ex)
                {
                    TransactionInfo.TransactionId = null;
                    MessageBox.Show("Kayıt Güncelleme Sırasında Hata Oluştu! \nHata Detayı : " + ex.Message);
                }

                if (_pageName == Extensions.PageNames.DocumentFlowPage.ToString())
                {
                    var documentFlowEntity = (DetailView<documentflow>) _detailEntity;

                    var documents = new BUS.DocumentManagement.Document();
                    var documentList = documents.GetEntityById(_documentId);

                    var user = new Users();
                    List<user> userList = null;

                    if (documentList != null && documentList.Count > 0)
                    {
                        userList = user.GetEntityById(documentList[0].CreateBy);
                    }

                    var paramValue = new ParameterValues();
                    List<parametervalue> paramValueList;

                    if (_isApproved)
                    {
                        paramValueList = paramValue.GetEntityByParameterId(35);

                        if (userList != null && userList.Count > 0 &&
                            paramValueList != null && paramValueList.Count > 0)
                        {
                            try
                            {
                                Extensions.SendMail(userList[0].Email,
                                                    "Döküman Onay Akışı Onay Bildirimi -  Otomatik E-Mail : Döküman Onayı",
                                                    String.Format(paramValueList[0].Value,
                                                                  documentFlowEntity.Entity.document.b_DocumentName,
                                                                  documentFlowEntity.Entity.document.parametervalue.Value,
                                                                  documentFlowEntity.Entity.document.parametervalue3.Value,
                                                                  documentFlowEntity.Entity.document.d_Version,
                                                                  documentFlowEntity.Entity.ModifyDate.ToShortDateString()));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Email Gönderme Sırasında Hata Oluştu! \nHata Detayı : " +
                                                ex.Message);
                            }
                        }
                    }
                    else
                    {
                        paramValueList = paramValue.GetEntityByParameterId(36);

                        if (userList != null && userList.Count > 0 &&
                            paramValueList != null && paramValueList.Count > 0)
                        {
                            try
                            {
                                Extensions.SendMail(userList[0].Email,
                                                    "Döküman Onay Akışı Onay Bildirimi -  Otomatik E-Mail : Döküman Red",
                                                    String.Format(paramValueList[0].Value, documentFlowEntity.Entity.document.b_DocumentName,
                                                                  documentFlowEntity.Entity.document.parametervalue.Value,
                                                                  documentFlowEntity.Entity.document.parametervalue3.Value,
                                                                  documentFlowEntity.Entity.d_ApprovalExplanation));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Email Gönderme Sırasında Hata Oluştu! \nHata Detayı : " +
                                                ex.Message);
                            }
                        }
                    }
                }

                Close();
            }
        }

        void ImageButtonClick(object sender, RoutedEventArgs e)
        {
            var txtBox = (TextBox)FindName("txtImagePath");

            var openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = "C:\\",
                Filter =
                    "image files (*.jpg)|*.jpg",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            var result = openFileDialog1.ShowDialog();

            if (result == true)
            {
                if (txtBox != null)
                {
                    txtBox.Text = openFileDialog1.FileName;
                    txtBox.IsEnabled = false;
                }
            }
        }
    }
}
